<template>
  <wrapper>
    <view class="inner-wrapper">
      <view style="height:17px"></view>
      <view
        class="realname-block"
        v-if="fromAdminConfirmedPostShow"
        style=" margin: 0 16px 17px 16px;"
      >
        <view class="realname-block-input-wrapper column">
          <view class="zjzhangpain">证件照片</view>
          <view class="realname-block-upload-wrapper">
            <view class="realname-block-upload" @tap="upload('positive', 'front')">
              <view class="realname-block-upload-image-box">
                <img class="realname-block-upload-image" :src="positiveSrc" lazy-load />
              </view>
              <view class="realname-block-upload-tip">添加身份证正面</view>
            </view>
            <view class="realname-block-upload" @tap="upload('reverse', 'back')">
              <view class="realname-block-upload-image-box">
                <img class="realname-block-upload-image" :src="reverseSrc" lazy-load />
              </view>
              <view class="realname-block-upload-tip">添加身份证背面</view>
            </view>
          </view>
        </view>
      </view>
      <!-- 身份认证 -->
      <view style="background:#fff;margin: 0 16px; border-radius: 8px;">
        <view style="padding: 16px;padding-bottom: 10px;">
          <view class="zjzhangpain">{{fromAdminConfirmedPostShow?"身份信息":"入职信息"}}</view>
        </view>
        <view style="text-align: center;padding-bottom:15px;" v-if="loadingBuild">
          <u-loading mode="flower" size="50"></u-loading>
          <view style="padding-top:30px;">加载中，请稍后...</view>
        </view>
        <XqFormBuild
          v-if="form"
          ref="form"
          :isShow="isShow"
          :dynamic-data="dynamicData"
          :form="form"
          :sortedKeys="sortedKeys"
          :form-config="formConfig"
          :rules="rules"
          :select-map="selectMap"
          :temp-data="tempData"
          @update="onFormUpdate"
          @inputFocused="onInputFocused"
        />
      </view>
      <view style="height:120px"></view>
    </view>
    <view class="block-buttonBox">
      <button class="block-button" @click="confirm" :disabled="conDisabled">确认</button>
    </view>
    <u-popup v-model="methodSetVisible" mode="bottom" border-radius="30">
      <view class="userinfo-appendix-menu-wrapper">
        <view class="userinfo-appendix-menu">
          <button
            class="userinfo-appendix-menu-item no-border"
            style="background: transparent; padding: 0;"
            open-type="getPhoneNumber"
            @getphonenumber="getPhoneNumber"
          >
            <img src="../images/weixin2.png" lazy-load />
            <span>微信一键绑定</span>
          </button>
          <button
            class="userinfo-appendix-menu-item no-border"
            style="background: transparent; padding: 0;"
            @tap="inputByHand"
          >
            <img src="../images/shoudong.png" lazy-load />
            <span>手动输入绑定</span>
          </button>
        </view>
        <view class="userinfo-appendix-menu-cancel" @tap="hideMenu">取消</view>
        <view style='background:#fafbfb;height:30px'></view>
      </view>
    </u-popup>
    <u-popup v-model="phoneSetVisible" mode="bottom" border-radius="30">
      <view class="register-wrapper" style="border-radius: 4px">
        <view class="register-entry-form-wrapper" style="padding: 30px 20px">
          <view style="color: #999; text-align: center; margin-bottom: 20px">修改手机号</view>
          <form @submit="submit">
            <view class="input-box">
              <input
                v-model="phoneTemp"
                placeholder="输入手机号"
                placeholder-class="placeholder"
                class="input"
                type="number"
              />
            </view>
            <view class="input-box">
              <input
                v-model="codeTemp"
                placeholder="输入验证码"
                placeholder-class="placeholder"
                class="input"
                type="text"
              />
              <button
                :disabled="disabledGetVerificationCode"
                class="input-button"
                @click="getVerificationCode"
              >{{ showTimmer ? second : text }}</button>
            </view>
            <button
              :disabled="loading"
              form-type="submit"
              class="button"
              :class="{disabled: loading}"
            >确定</button>
          </form>
        </view>
      </view>
    </u-popup>
    <u-popup v-model="methodChannelSetVisible" mode="bottom" border-radius="30" z-index="99">
      <view class="channelIdBox">
        <view class="channelIdBoxTop">
          <text class="channelIdBoxTopXZQD">选择渠道</text>
          <view>
            <view class="channelIdBoxTopBet" @click="channelIdValueCancel">取消</view>
            <view class="channelIdBoxTopBet6A" @click="channelIdValueOK">确定</view>
          </view>
        </view>
        <view style="height:40px"></view>
        <view style="padding:16px">
          <u-search placeholder="搜索渠道" v-model="keyword" :show-action="false"></u-search>
        </view>
        <view class="channelIdBoxHei">
          <view style="height:100%">
            <scroll-view scroll-y="true">
              <u-radio-group
                wrap="true"
                size="40"
                v-model="channelIdValue"
                @change="radioGroupChange"
              >
                <u-radio
                  style="margin-bottom: 12px;"
                  v-for="(item, index) in channelIdList"
                  :key="index"
                  :active-color="settings.theme"
                  :name="item.value"
                  :disabled="item.disabled"
                >{{item.label}}</u-radio>
              </u-radio-group>
            </scroll-view>
          </view>
        </view>
      </view>
    </u-popup>
    <u-modal
      v-model="expireShow"
      :confirmColor="settings.theme"
      title="二维码已过期"
      content="请联系公司管理员"
      :show-cancel-button="false"
    ></u-modal>
    <u-modal v-model="errShow" :confirmColor="settings.theme" :content="errContent"></u-modal>
  </wrapper>
</template>
<script>
import XqFormBuild from "./xqFormIndex";
import { buildForm, handleTailValue } from "@/components/XqForm/utils";
import { basicsPages } from "./dynamic";
import Wrapper from "@/components/Wrapper";
import {
  getByKey,
  selectOpenTemplate,
  batchConfirmToJoin
} from "./api";
import { uploadSiteImgIdCard } from "@/services/common";
import {
  checkPhone,
  checkVerificationCode
} from "@/utils/validate";
import { getPhoneNumber } from "@/services/auth";
import request from "@/utils/request";
import { BASE_URL } from "@/settings";
import { smsSendReq, smsVerifyReq } from "./api";
import { additionalArr, joinDateDefaultItem } from "./funcs";
import { formatFullDate } from "@/utils/tools";
import { mapState } from 'vuex'
export default {
  name: "",
  components: {
    Wrapper,
    XqFormBuild
  },
  data() {
    return {
      errShow: false,
      errContent: "",
      loadingBuild: false,
      fromAdminConfirmedPostShow: true,
      expireShow: false,
      options: "",
      timer: null,
      myVar: null,
      postType: "5",
      formalType: "2",
      joinDate: formatFullDate(),
      probationDays: 0,
      turnStraightDate: formatFullDate(),
      conDisabled: false,
      sortedKeys: [],
      additionalArr,
      isShow: false,
      dynamicData: {},
      form: null,
      formConfig: null,
      rules: null,
      selectMap: null,
      tempData: {},
      moduleData: {},
      customTemplateFieldVOList: [],
      codeInput: "",
      state: "",
      selectorShow: false,
      nationList: [],
      nationList1: "",
      positiveSrc:
        "https://res.zhixinren.work/prod/ede30058-a8fe-44a6-b377-08d05f3b768c/8c9e5274-9e25-41b3-8075-b388d2138723.png",
      // ../static/shenfenzhengzheng.png
      reverseSrc:
        "https://res.zhixinren.work/prod/fbec5706-a17c-4ef9-98df-efc86593d22a/e2e1b861-b5eb-437e-818b-a6915c65140a.png",
      // require("../static/shenfenzhengbei.png"),
      positiveUrl: "",
      reverseUrl: "",
      captureUrl: "",
      bankUrl: "",
      faceUrl: "",
      name: "",
      idCard: "",
      cardNo: "",
      phone: "",
      // nation: "",
      nativeLocation: "",
      remark: "",
      openShow: "",
      stateShow: "",
      codeVisible: false,
      code: "",
      stateVal: {},
      phoneSetVisible: false, // 以下新增验证手机号流程新增变量
      methodSetVisible: false,
      phoneTemp: "",
      codeTemp: "",
      showTimmer: false,
      second: 60,
      text: "获取验证码",
      disabledGetVerificationCode: false,
      login_code: "",
      loading: false, // end
      methodChannelSetVisible: false, // 渠道相关
      channelIdValue: "",
      keyword: "",
      channelIdListAll: [],
      channelIdList: [], //
      status: null,
      flowId: null,
      companyId: null,
      channelId: null,
      siteId: null,
      operationUserId: null,
      uploadImgRecord: {}
    };
  },
  props: {
    paramete: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    ...mapState(['settings'])
  },
  watch: {
    sortedKeys(newVal, oldVal) {
      if (oldVal.length > newVal.length || newVal.length > oldVal.length) {
        this.isShow = false;
        this.$nextTick(() => {
          this.isShow = true;
        });
      }
    },
    keyword(val) {
      this.channelIdList = this.channelIdListAll.filter(
        z => z.label.indexOf(val) !== -1
      );
    },
    paramete: {
      handler(options) {
        console.log(options);
      },
      immediate: true,
      deep: true
    }
  },
  onLoad(options) {
     if (options) {
          this.source = options.source;
          if (options.params) {
            // 二维码
            uni.setStorageSync("token", "");
            this.openShow = "QRCodeInvitation";
            getByKey({ key: options.params }).then(res => {
              if (res) {
                console.log("expireDate", res, res.expireDate);
                this.stateVal = res;
                if (this.source === "fromPC") {
                  this.status = parseInt(res.status);
                  this.flowId = res.flowId;
                  this.companyId = res.companyId;
                  if (res.channelId) {
                    this.channelId = res.channelId;
                    this.channelIdValue = this.channelId; // 渠道搜索框里面选中
                    this.tempData = {
                      ...this.tempData,
                      channelId: res.channelId
                    };
                  }
                  this.siteId = res.siteId;
                  this.operationUserId = res.operationUserId;
                  // 工作性质默认是 5（其他）
                  this.postType = res.postType ? res.postType + "" : "5";
                  this.formalType = res.formalType ? res.formalType + "" : "2";
                  // expireDate 没有，意思是永久有效
                   
                  if (res.expireDate) {
                    const currDate =new Date().getTime()
                   console.log('123' , currDate,res.expireDate)
                    // if (currDate > new Date(res.expireDate)) {
                      if (currDate > res.expireDate) {
                      // 已过期
                      this.expireShow = true;
                    }
                  }
                } else {
                  this.source = "fromQrCode";
                  if (res.channelId) {
                    this.channelId = res.channelId;
                    this.channelIdValue = this.channelId; // 渠道搜索框里面选中
                    this.tempData = {
                      ...this.tempData,
                      channelId: res.channelId
                    };
                  }
                }
                this.selectOpenTemplate();
              } else {
                this.expireShow = true;
              }
            });
          } else if (options.state) {
            if (options.empInfoDetails) {
              // 确认到岗
              this.source = "fromAdminConfirmedPost";
              this.fromAdminConfirmedPostShow = false;
              this.stateVal = JSON.parse(options.empInfoDetails);
            } else {
              // 手动录入
              this.source = "fromAdminManually";
              this.stateVal = JSON.parse(options.stateVal);
            }
            this.stateShow = options.state;
            if (this.stateVal.channelId) {
              this.channelId = this.stateVal.channelId;
              this.channelIdValue = this.channelId; // 渠道搜索框里面选中
              this.tempData = {
                ...this.tempData,
                channelId: this.stateVal.channelId
              };
            }
            this.selectOpenTemplate();
          } else {
            // 动态码
            this.source = "fromAdminDynamicCode";
            this.openShow = "home";
            uni.setStorageSync("token", "");
            this.stateVal = JSON.parse(options.siteObject);
            if (this.stateVal.channelId) {
              this.channelId = this.stateVal.channelId;
              this.channelIdValue = this.channelId; // 渠道搜索框里面选中
              this.tempData = {
                ...this.tempData,
                channelId: this.stateVal.channelId
              };
            }
            this.selectOpenTemplate();
          }
        }
  },
  mounted() {
    console.log(this.source, "source");
  },
  methods: {
    channelIdValueCancel() {
      this.$set(this.form, "channelId", "");
      this.channelId = "";
      this.channelIdValue = "";
      this.keyword = "";
      this.methodChannelSetVisible = false;
    },
    channelIdValueOK() {
      this.methodChannelSetVisible = false;
    },
    radioGroupChange(e) {
      const id = this.channelIdList.filter(z => z.value === e);
      this.tempData = {
        ...this.tempData,
        channelId: id[0].value
      };
      this.channelId = e;
    },
    showMenu() {
      this.methodSetVisible = true;
    },

    inputByHand() {
      this.phoneSetVisible = true;
      this.hideMenu();
    },

    hideMenu() {
      this.methodSetVisible = false;
    },
    getPhoneNumber(e) {
      if (e.target.errMsg === "getPhoneNumber:ok") {
        // 同意授权
        if (e.target && e.target["iv"] && e.target["encryptedData"]) {
          const data = {
            jsCode: this.login_code,
            iv: e.target.iv,
            encryptedData: e.target.encryptedData,
            terminalType: "B"
          };
          getPhoneNumber(data)
            .then(res => {
              this.phoneSetVisible = false;
              this.hideMenu();
              this.$refs.form.reset();
              this.tempData = {
                ...this.tempData,
                phone: res.phoneNumber
              };
              this.$set(this.form, "phone", res.phoneNumber);
              this.isShow = false;
              this.$nextTick(() => {
                this.isShow = true;
              });
              console.log("this.form", this.form, this.tempData);
            })
            .catch(err => {
              // 弹框提示
              uni.showToast({
                title: err,
                icon: "none",
                duration: 2000
              });
            });
        } else {
          uni.showToast({
            title: "微信授权失败",
            icon: "none",
            duration: 2000
          });
        }
      } else {
        // 拒绝手机号授权
        uni.showToast({
          title: "手机号授权失败",
          icon: "none",
          duration: 2000
        });
      }
    },
    getVerificationCode() {
      // 手机号格式校验
      if (checkPhone(this.phoneTemp)) {
        smsSendReq(this.phoneTemp)
          .then(res => {
            uni.showToast({
              title: "验证码发送成功",
              icon: "none",
              duration: 2000
            });
            this.showTimmer = true;
            this.disabledGetVerificationCode = true;
            this.timer = setInterval(() => {
              this.second = this.second - 1;
              if (this.second === 0) {
                this.disabledGetVerificationCode = false;
                this.showTimmer = false;
                this.second = 60;
                this.text = "重新获取";
                clearInterval(this.timer);
              }
            }, 1000);
          })
          .catch(err => {
            uni.showToast({
              title: err.message,
              icon: "none",
              duration: 2000
            });
          });
      } else {
        uni.showToast({
          title: "手机号格式错误",
          icon: "none",
          duration: 2000
        });
      }
    },
    submit() {
      if (checkPhone(this.phoneTemp) && checkVerificationCode(this.codeTemp)) {
        this.loading = true;
        smsVerifyReq({
          phone: this.phoneTemp,
          code: this.codeTemp
        })
          .then(res => {
            this.phoneSetVisible = false;
            this.hideMenu();
            this.$refs.form.reset();
            this.tempData = {
              ...this.tempData,
              phone: this.phoneTemp
            };
            this.$set(this.form, "phone", this.phoneTemp);
            console.log("this.form", this.form, this.tempData);
            this.isShow = false;
            this.$nextTick(() => {
              this.isShow = true;
            });
            this.loading = false;
            this.showTimmer = false;
            this.second = 60;
            this.text = "重新获取";
            this.disabledGetVerificationCode = false;
            this.phoneTemp = "";
            this.codeTemp = "";
            clearInterval(this.timer);
          })
          .catch(err => {
            this.loading = false;
            uni.showToast({
              title: err.message,
              icon: "none",
              duration: 2000
            });
          });
      } else {
        if (!checkPhone(this.phoneTemp)) {
          uni.showToast({
            title: "手机号格式错误",
            icon: "none",
            duration: 2000
          });
        } else if (!checkVerificationCode(this.codeTemp)) {
          uni.showToast({
            title: "验证码格式错误",
            icon: "none",
            duration: 2000
          });
        }
      }
    },

    onInputFocused(key) {
      let myVar = null;
      if (key === "phone") {
        myVar = setInterval(function() {
          uni.hideKeyboard(); // 隐藏软键盘
        }, 5);
        uni.login({
          success: res => {
            // 获取code
            this.login_code = res.code;
          }
        });
        this.showMenu();
        setTimeout(function() {
          clearInterval(myVar);
        }, 800);
      } else if (key === "channelId") {
        setTimeout(function() {
          clearInterval(myVar);
        }, 800);
        this.methodChannelSetVisible = true;
      } else {
        setTimeout(function() {
          clearInterval(myVar);
        }, 800);
      }
    },
    selectOpenTemplate() {
      let data = {};
      if (this.source === "fromPC") {
        data = {
          siteId: this.stateVal.siteId,
          companyId: this.stateVal.companyId,
          moduleCode: "waitJob"
        };
      } else if (this.source === "fromAdminManually") {
        data = {
          companyId:
            this.stateShow === "add" ? this.stateVal.subjectId : "site",
          moduleCode: this.stateShow === "add" ? "waitJob" : "checkIn"
        };
      } else if (this.source === "fromAdminConfirmedPost") {
        data = {
          companyId: this.stateVal.companyId,
          moduleCode: "onJob"
        };
      } else {
        data = {
          siteId: this.stateVal.siteId,
          companyId:
            this.stateVal.type === 2 ? this.stateVal.companyId : "site",
          moduleCode: this.stateVal.type === 2 ? "waitJob" : "checkIn"
        };
      }
      this.loadingBuild = true;
      selectOpenTemplate(data)
        .then(res => {
          const additionalFieldsListVOS = res.additionalFieldsListVOS.map(z => {
            z.fieldCode = z.id;
            return z;
          });
          // 如果模板中有员工状态但是没有入职日期 ，需要加上
          const tempFields = res.customTemplateFieldVOList.map(
            item => item.fieldCode
          );
          const needDefaultJoinDate =
            tempFields.includes("formalType") &&
            !tempFields.includes("joinDate");
          this.customTemplateFieldVOList = [
            ...res.customTemplateFieldVOList,
            ...(needDefaultJoinDate ? [joinDateDefaultItem] : []),
            ...additionalArr,
            ...additionalFieldsListVOS
          ].sort((a, b) => {
            return a.sort - b.sort;
          });
          // 渠道搜索
          const channelIdListAll = this.customTemplateFieldVOList.filter(
            i => i.fieldCode === "channelId"
          );
          if (channelIdListAll.length !== 0) {
            this.channelIdListAll = channelIdListAll[0].dropDownEnumList.map(
              i => {
                i.disabled = false;
                return i;
              }
            );
          } else {
            this.channelIdListAll = [];
          }
          this.channelIdList = this.channelIdListAll;
          console.log(this.channelIdList);
          this.getListCompanyModuleCodes(this.customTemplateFieldVOList, true);
        })
        .catch(err => {
          this.isShow = false;
          console.log("ERROR", err);
        });
    },
    getListCompanyModuleCodes(element) {
      uni.showLoading({
        title: "表单加载中..."
      });
      const { form, formConfig, rules, selectMap } = buildForm(
        basicsPages([...element])
      );
      let formArr = Object.keys(form);
      formArr = formArr.filter(key => {
        if (key === "probationDays") {
          return false;
        } else if (key === "turnStraightDate") {
          if (formArr.includes("formalType")) {
            return true;
          } else {
            return false;
          }
        }
        return true;
      });
      const formArrShow = [];
      element.filter(z => {
        const a = formArr.find(y => y === z.fieldCode + "");
        if (a) {
          if (a === "channelId") {
            if (this.channelIdList.length !== 0) {
              formArrShow.push(a);
            }
          } else {
            formArrShow.push(a);
          }
        }
      });
      this.loadingBuild = false;
      this.sortedKeys = formArrShow;
      this.formConfig = formConfig;
      this.rules = rules;
      this.form = form;
      this.selectMap = selectMap;
      this.$nextTick(() => {
        this.$refs.form.init();
      });
      if (this.form && Object.keys(this.form).includes("postType")) {
        this.$set(this.form, "postType", this.postType);
      }
      if (this.form && Object.keys(this.form).includes("formalType")) {
        this.$set(this.form, "formalType", this.formalType);
      }
      if (this.form && Object.keys(this.form).includes("joinDate")) {
        this.$set(this.form, "joinDate", this.joinDate);
      }
      if (this.form && Object.keys(this.form).includes("probationDays")) {
        this.$set(this.form, "probationDays", this.probationDays);
      }
      if (this.form && Object.keys(this.form).includes("turnStraightDate")) {
        this.$set(this.form, "turnStraightDate", this.turnStraightDate);
      }
      if (this.source === "fromAdminConfirmedPost") {
        this.$set(this.formConfig.name.customize, "disabled", true);
        this.$set(this.formConfig.phone.customize, "disabled", true);
        this.$set(this.formConfig.idCard.customize, "disabled", true);
        Object.keys(this.form).map(z => {
          if (this.stateVal[z]) {
            this.$set(
              this.form,
              z,
              typeof this.stateVal[z] === "number" &&
                this.stateVal[z].toString().length === 1
                ? this.stateVal[z].toString()
                : this.stateVal[z]
            );
          }
        });
      }
      this.isShow = false;
      this.$nextTick(() => {
        this.isShow = true;
      });
      uni.hideLoading();
    },
    afterTime(dateStr, dayCount) {
      if (dateStr) {
        var tempDate = new Date(dateStr.replace(/-/g, "/")); // 把日期字符串转换成日期格式
        var resultDate = new Date((tempDate / 1000 + 86400 * dayCount) * 1000); // 增加n天后的日期
        var resultDateStr =
          resultDate.getFullYear() +
          "-" +
          (resultDate.getMonth() + 1) +
          "-" +
          resultDate.getDate(); // 将日期转化为字符串格式
        return resultDateStr;
      }
    },
    confirm() {
      this.$refs.form
        .getData()
        .then(res => {
          for (const key in res) {
            if (
              res[key] &&
              typeof res[key] === "string" &&
              res[key].length === 10 &&
              key !== "birthday" &&
              key !== "endDate" &&
              key !== "startDate"
            ) {
              if (res[key].split("-").length - 1 === 2) {
                res[key] += " 00:00:00";
              }
            }
          }
          const dataKeys = []; // 自定义的
          let dataKeysDefauit = {}; // 系统默认
          Object.keys(res).map(z => {
            if (!isNaN(parseInt(z))) {
              const data = {
                id: z,
                fieldName: this.formConfig[z].label,
                content: res[z]
              };
              dataKeys.push(data);
            } else {
              dataKeysDefauit = Object.assign({ [z]: res[z] }, dataKeysDefauit);
            }
          });
          const valueShow = Object.assign(dataKeysDefauit, {
            addEmpFieldList: dataKeys
          });
          if (this.source === "fromAdminConfirmedPost") {
            this.getBatchConfirmToJoin(valueShow);
          } else {
            this.verifyIdCard(valueShow);
          }
        })
        .catch(err => {
          console.log("debug log --> ", err);
        });
    },
    getTime(time) {
      time = time.replace(/-/g, ":").replace(" ", ":");
      time = time.split(":");
      const timeShow = new Date(
        time[0],
        time[1] - 1,
        time[2],
        time[3],
        time[4],
        time[5]
      );
      return timeShow;
    },
    getBatchConfirmToJoin(valueShow) {
      // console.log(valueShow);
      const joinDate = Date.parse(new Date(this.getTime(valueShow.joinDate)));
      const turnStraightDate = Date.parse(
        new Date(this.getTime(valueShow.turnStraightDate))
      );
      const joinDate1 = joinDate.valueOf(joinDate);
      const turnStraightDate1 = turnStraightDate.valueOf(turnStraightDate);
      if (joinDate1 > turnStraightDate1) {
        valueShow.turnStraightDate = valueShow.joinDate;
      }
      // console.log(joinDate1, turnStraightDate1);
      const data = { ...this.stateVal, ...valueShow };
      batchConfirmToJoin([data])
        .then(res => {
          console.log(res);
          uni.showToast({
            title: "操作成功",
            icon: "success",
            duration: 2000
          });
          setTimeout(() => {
            uni.navigateBack({
              delta: 1
            });
          }, 1000);
        })
        .catch(err => {
          console.log(err);
        });
    },
    onFormUpdate(tail, value) {
      handleTailValue(tail, value, this);
      this.getFormChange(tail, value);
    },
    getFormChange(tail, value) {
      if (tail === "form.idCard") {
        value = value ? value.toUpperCase() : null;
        if (this.form && Object.keys(this.form).includes("idCard")) {
          this.$set(this.form, "idCard", value);
        }
      } else if (tail === "form.formalType" && value === "试用") {
        if (!this.sortedKeys.includes("turnStraightDate")) {
          this.sortedKeys.map((z, index) => {
            if (z === "formalType") {
              const tempKeys = [...this.sortedKeys];
              tempKeys.splice(index + 1, 0, "turnStraightDate");
              this.sortedKeys = tempKeys;
            }
          });
        }
        if (!this.sortedKeys.includes("probationDays")) {
          this.sortedKeys.map((z, index) => {
            if (z === "formalType") {
              const tempKeys = [...this.sortedKeys];
              tempKeys.splice(index + 1, 0, "probationDays");
              this.sortedKeys = tempKeys;
            }
          });
          this.$set(this.form, "probationDays", 0);
        }
        this.$set(this.formConfig.turnStraightDate, "isRequired", false);
        this.$set(this.formConfig.turnStraightDate.customize, "disabled", true);
      } else if (tail === "form.formalType" && value === "正式") {
        this.$set(this.formConfig.turnStraightDate, "isRequired", true);
        this.$set(
          this.formConfig.turnStraightDate.customize,
          "disabled",
          false
        );
        this.sortedKeys = this.sortedKeys.filter(
          key => key !== "probationDays"
        );
      } else if (tail === "form.probationDays" && value) {
        if (this.$refs.form.form.joinDate) {
          const newTime = this.afterTime(
            this.$refs.form.form.joinDate,
            Number(value)
          );
          if (
            this.form &&
            Object.keys(this.form).includes("turnStraightDate")
          ) {
            this.$set(this.form, "turnStraightDate", newTime);
            this.$set(this.tempData, "turnStraightDate", newTime);
          }
        }
      } else if (tail === "form.joinDate" && value) {
        if (
          value &&
          this.form.turnStraightDate &&
          this.sortedKeys.includes("turnStraightDate")
        ) {
          const joinDate = Date.parse(
            new Date(this.getTime(value + " 00:00:00"))
          );
          const turnStraightDate = Date.parse(
            new Date(this.getTime(this.form.turnStraightDate + " 00:00:00"))
          );
          const joinDate1 = joinDate.valueOf(joinDate);
          const turnStraightDate1 = turnStraightDate.valueOf(turnStraightDate);
          if (joinDate1 > turnStraightDate1) {
            uni.showToast({
              title: "预计转正日期要大于入职日期,请重新选择入职日期",
              icon: "none",
              duration: 3000
            });
            this.$set(this.form, "joinDate", "");
          }
        }
        if (
          this.$refs.form.form &&
          this.$refs.form.form.formalType === "试用"
        ) {
          const newTime = this.afterTime(
            value,
            Number(this.$refs.form.form.probationDays)
          );
          this.$set(
            this.formConfig.turnStraightDate.customize,
            "disabled",
            true
          );
          if (
            this.form &&
            Object.keys(this.form).includes("turnStraightDate")
          ) {
            this.$set(this.form, "turnStraightDate", newTime);
            this.$set(this.tempData, "turnStraightDate", newTime);
          }
        }
      } else if (tail === "form.turnStraightDate" && value) {
        if (
          value &&
          this.form.joinDate &&
          this.sortedKeys.includes("joinDate")
        ) {
          const joinDate = Date.parse(
            new Date(this.getTime(this.form.joinDate + " 00:00:00"))
          );
          const turnStraightDate = Date.parse(
            new Date(this.getTime(value + " 00:00:00"))
          );
          const joinDate1 = joinDate.valueOf(joinDate);
          const turnStraightDate1 = turnStraightDate.valueOf(turnStraightDate);
          if (joinDate1 > turnStraightDate1) {
            uni.showToast({
              title: "预计转正日期要大于入职日期,请重新选择预计转正日期",
              icon: "none",
              duration: 3000
            });
            this.$set(this.form, "turnStraightDate", "");
          }
        }
      }
    },
    // 身份证实名认证
    verifyIdCard(res) {
      uni.showLoading({
        mask: true,
        title: "认证中..."
      });
      let data = {};
      if (this.source === "fromPC") {
        data = {
          annexIdCard: `${this.positiveUrl}${
            this.positiveUrl && this.reverseUrl ? "," : ""
          }${this.reverseUrl}`,
          ...this.uploadImgRecord,
          ...res
        };
        data.employType = 1; //
        data.status = this.status; // 在职
        data.siteId = this.siteId;
        data.operationUserId = this.operationUserId;
        data.companyId = this.companyId;
        data.channelId = data.channelId || this.channelId;
        data.idCardBack = this.positiveUrl;
        data.idCardFront = this.reverseUrl;
        if (this.flowId !== null && this.flowId !== undefined) {
          data.flowId = this.flowId;
        }
        data.turnStraightDate =
          data.turnStraightDate ||
          this.afterTime(data.joinDate, data.probationDays);
      } else if (
        this.source === "fromAdminDynamicCode" ||
        this.source === "fromQrCode"
      ) {
        data = {
          source: this.stateVal.type === 2 ? null : "预登记",
          idcardfront: this.reverseUrl,
          idcardback: this.positiveUrl,
          idCardBack: this.positiveUrl,
          idCardFront: this.reverseUrl,
          companyId: this.stateVal.companyId,
          annexIdCard: `${this.positiveUrl}${
            this.positiveUrl && this.reverseUrl ? "," : ""
          }${this.reverseUrl}`,
          ...this.uploadImgRecord,
          ...res,
          channelId: res.channelId || this.stateVal.channelId,
          status: this.stateVal.type === 2 ? "1" : res.status,
          turnStraightDate:
            res.turnStraightDate || this.turnStraightDate || formatFullDate(),
          userId: this.stateVal.type === 2 ? null : this.stateVal.userId,
          operationUserId: this.stateVal.operationUserId,
          siteId: this.stateVal.siteId,
          code: this.stateVal.code
        };
      } else if (this.source === "fromAdminManually") {
        data = {
          source: this.stateShow === "add" ? null : "预登记",
          name: this.name,
          idcardfront: this.reverseUrl,
          idcardback: this.positiveUrl,
          idCardBack: this.positiveUrl,
          idCardFront: this.reverseUrl,
          companyId: this.stateVal.subjectId,
          annexIdCard: `${this.positiveUrl}${
            this.positiveUrl && this.reverseUrl ? "," : ""
          }${this.reverseUrl}`,
          // annexIdCard:
          //   this.reverseUrl && this.positiveUrl
          //     ? `${this.reverseUrl},${this.positiveUrl}`
          //     : null,
          status: this.stateShow === "add" ? "1" : null,
          channelId: res.channelId || this.stateVal.channelId,
          ...this.uploadImgRecord,
          ...res,
          turnStraightDate:
            res.turnStraightDate || this.turnStraightDate || formatFullDate()
        };
      }
      data.formalType = res.formalType || this.formalType || "2";
      data.postType = res.postType || this.postType || "5";
      data.joinDate = res.joinDate || this.joinDate || formatFullDate();
      data.probationDays = res.probationDays || this.probationDays || 0;

      let url = "";
      if (this.source === "fromPC") {
        url = "/hr/api/v1/empInfos/saveEmpInfoAndRuleForMini";
      } else if (
        this.source === "fromAdminDynamicCode" ||
        this.source === "fromQrCode"
      ) {
        url =
          this.stateVal.type === 2
            ? "/hr/api/v1/empInfos/saveEmpInfoAndRuleForMini"
            : "/hr/api/v1/checkInPeoples/saveForMini";
      } else if (this.source === "fromAdminManually") {
        url =
          this.stateShow === "add"
            ? "/hr/api/v1/empInfos/saveEmpInfoAndRule"
            : "/hr/api/v1/checkInPeoples";
      }
      this.conDisabled = true;
      request({
        url: `${BASE_URL}${url}`,
        method: "post",
        data
      })
        .then(res => {
          uni.hideLoading();
          console.log("debug log --> ", res);
          uni.showToast({
            title: "操作成功",
            icon: "none",
            duration: 1500
          });
          if (this.source === "fromAdminManually") {
            setTimeout(() => {
              this.conDisabled = false;
              uni.reLaunch({
                url: "/pages/home/index"
              });
            }, 1000);
          } else {
            setTimeout(() => {
              this.conDisabled = false;
              uni.reLaunch({
                url: "/pages/index/index"
              });
            }, 1000);
          }
        })
        .catch(err => {
          this.conDisabled = false;
          uni.hideLoading();
          console.log("debug log --> ", err);
          uni.showToast({
            title: err.msg,
            icon: "none",
            duration: 5000
          });
          // this.errShow = true;
          // this.errContent = err.toString();
        });
    },
    getNowFormatDate() {
      var date = new Date();
      var seperator1 = "-";
      var seperator2 = ":";
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate =
        date.getFullYear() + seperator1 + month + seperator1 + strDate;

      return currentdate;
    },
    upload(type, e) {
      uni.chooseImage({
        count: 1,
        success: imageRes => {
          const tempFilePaths = imageRes.tempFilePaths;
          uni.showLoading({
            title: "文件上传中...",
            mask: true
          });
          uploadSiteImgIdCard(tempFilePaths[0], e)
            .then(res => {
              const urlShow = res.url;
              console.log("res", res);

              uni.hideLoading();
              if (JSON.stringify(res) !== "{}" && res.name) {
                this.name = res.name;
                this.idCard = res.idcard;
                if (this.sortedKeys.includes("nativeLocation")) {
                  this.nativeLocation = res.address;
                  this.$set(this.form, "nativeLocation", this.nativeLocation);
                }
                if (this.sortedKeys.includes("nation")) {
                  this.nation = res.nation;
                  this.$set(this.form, "nation", `${this.nation}族`);
                  this.$set(this.tempData, "nation", `${this.nation}族`);
                }
                if (this.source === "fromPC") {
                  this.$set(this.form, "idCard", this.idCard);
                } else {
                  if (this.stateVal.type === 2 || this.stateShow === "add") {
                    this.$set(this.form, "idCard", this.idCard);
                  } else {
                    this.$set(this.form, "idcard", this.idCard);
                  }
                }
                if (this.sortedKeys.includes("birthday")) {
                  this.$set(
                    this.form,
                    "birthday",
                    `${res.birthday.substring(0, 4)}-${res.birthday.substring(
                      4,
                      6
                    )}-${res.birthday.substring(6, 8)}`
                  );
                }
                if (this.sortedKeys.includes("photo")) {
                  if (this.form.photo) {
                    this.form.photo =
                      this.form.photo
                        .split(",")
                        .filter(z => z !== this.positiveUrl) + "";
                  }
                  this.$set(
                    this.form,
                    "photo",
                    `${
                      this.form.photo
                        ? this.form.photo + "," + res.url
                        : res.url
                    }`
                  );
                }
                if (this.sortedKeys.includes("annexIdCard")) {
                  if (this.form.annexIdCard) {
                    this.form.annexIdCard =
                      this.form.annexIdCard
                        .split(",")
                        .filter(z => z !== this.positiveUrl) + "";
                  }
                  this.$set(
                    this.form,
                    "annexIdCard",
                    `${
                      this.form.annexIdCard
                        ? this.form.annexIdCard + "," + res.url
                        : res.url
                    }`
                  );
                }
                this.$set(this.form, "name", this.name);
                this.uploadImgRecord = {
                  ...this.uploadImgRecord,
                  nation: `${res.nation}族`,
                  nativeLocation: res.address,
                  birthday: `${res.birthday.substring(
                    0,
                    4
                  )}-${res.birthday.substring(4, 6)}-${res.birthday.substring(
                    6,
                    8
                  )}`
                };
              }
              if (JSON.stringify(res) !== "{}" && res.expiryDay) {
                const issuanceDay = res.issuanceDay;
                const expiryDay = res.expiryDay;
                const startDate = `${issuanceDay.substring(
                  0,
                  4
                )}-${issuanceDay.substring(4, 6)}-${issuanceDay.substring(
                  6,
                  8
                )}`;
                const endDate = `${expiryDay.substring(
                  0,
                  4
                )}-${expiryDay.substring(4, 6)}-${expiryDay.substring(6, 8)}`;
                // startDate endDate用于预登记
                // cardStartDate cardEndDate 用于待入职和入职
                if (this.sortedKeys.includes("startDate")) {
                  this.$set(this.form, "startDate", startDate);
                }
                if (this.sortedKeys.includes("endDate")) {
                  this.$set(this.form, "endDate", endDate);
                }
                if (this.sortedKeys.includes("cardStartDate")) {
                  this.$set(this.form, "cardStartDate", startDate);
                }
                if (this.sortedKeys.includes("cardEndDate")) {
                  this.$set(this.form, "cardEndDate", endDate);
                }
                if (this.sortedKeys.includes("issuedBy")) {
                  this.$set(this.form, "issuedBy", res.issuanceDepartment);
                }
                if (this.sortedKeys.includes("photo")) {
                  if (this.form.photo) {
                    this.form.photo =
                      this.form.photo
                        .split(",")
                        .filter(z => z !== this.reverseUrl) + "";
                  }
                  this.$set(
                    this.form,
                    "photo",
                    `${
                      this.form.photo
                        ? this.form.photo + "," + res.url
                        : res.url
                    }`
                  );
                }
                if (this.sortedKeys.includes("annexIdCard")) {
                  if (this.form.annexIdCard) {
                    this.form.annexIdCard =
                      this.form.annexIdCard
                        .split(",")
                        .filter(z => z !== this.reverseUrl) + "";
                  }
                  this.$set(
                    this.form,
                    "annexIdCard",
                    `${
                      this.form.annexIdCard
                        ? this.form.annexIdCard + "," + res.url
                        : res.url
                    }`
                  );
                }
                this.uploadImgRecord = {
                  ...this.uploadImgRecord,
                  issuedBy: res.issuanceDepartment,
                  startDate: startDate,
                  endDate: endDate,
                  cardStartDate: startDate,
                  cardEndDate: endDate
                };
              }
              this[`${type}Url`] = `${urlShow}`;
              this[`${type}Src`] = `${urlShow}?token=${uni.getStorageSync(
                "token"
              )}`;
            })
            .catch(err => {
              uni.hideLoading();
              uni.showToast({
                title: err.message,
                icon: "none",
                duration: 1500
              });
            });
        },
        fail: err => {
          uni.showToast({
            title: err.message,
            icon: "none",
            duration: 1500
          });
        }
      });
    }
  }
};
</script>
<style lang="scss">
.inner-wrapper {
  width: 100vw;
  min-height: 100vh;
  background: #f8f8f8;
  overflow-y: auto;
}
.realname-block {
  border-radius: 8px;
  margin-bottom: 20px;
  padding: 16px;
  background-color: #ffffff;
  .realname-block-input-wrapper {
    display: flex;
    flex-direction: row;
    padding: 0;
    justify-content: space-between;
    color: #ccc;
    &.border {
      border-bottom: 0.5px solid rgba(0, 0, 0, 0.1);
    }
    &.column {
      flex-direction: column;
      justify-content: flex-start;
    }
    .borderLast {
      border-bottom: 0px;
    }
    .realname-block-input-label {
      &:before {
        content: "*";
        color: #fa5051;
        margin-right: 5px;
      }
    }
    .realname-block-input {
      text-align: right;
    }
    .realname-block-upload-wrapper {
      width: 100%;
      margin-top: 10px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      .realname-block-upload {
        width: 48%;
        box-sizing: border-box;
        border: 1px solid rgba(0, 0, 0, 0.1);
        border-radius: 5px;
        overflow: hidden;
        .realname-block-upload-image {
          width: 100%;
          height: 78px;
          background-color: #f7f7f7;
          padding: 8px 16px;
          box-sizing: border-box;
        }
        .realname-block-upload-tip {
          width: 100%;
          color: #55565d;
          text-align: center;
          line-height: 24px;
          height: 24px;
          font-size: 12px;
          padding-bottom: 5px;
        }
      }
    }
  }
}
.block-wrapper {
  padding-left: 15px;
  padding-right: 15px;
  padding-bottom: 15px;
  &.nph {
    padding-left: 0;
    padding-right: 0;
  }
  &.pt {
    padding-top: 15px;
  }
  .block-inner {
    background-color: #ffffff;
    border-radius: 8px;
    background-color: #ffffff;
    border-radius: 8px;
    padding: 16px;
    padding-top: 0;
    &.theme {
      background-color: #1890ff;
    }
    &.pt {
      padding-top: 15px;
    }
    &.input {
      padding-top: 13px;
      padding-bottom: 5px;
    }
    &.mt {
      margin-top: 15px;
    }
  }

  .block-tip {
    font-size: 12px;
    color: #999;
    line-height: 35px;
    padding: 0 10px;
    &.np {
      line-height: 1;
      padding: 0;
    }
  }
  .block-inner-content {
    margin-top: 15px;
    color: #999;
    font-size: 14px;
    line-height: 1.75;
  }
  .block-input-wrapper {
    display: flex;
    flex-direction: row;
    padding: 10px 0;
    justify-content: space-between;
    // color: #999;
    font-size: 14px;
    align-items: center;
    &.border {
      border-bottom: 0.5px solid rgba(0, 0, 0, 0.1);
    }
    &.column {
      flex-direction: column;
      justify-content: flex-start;
    }
    .borderLast {
      border-bottom: 0px;
    }
    .block-input-label {
      width: 80px;
      &.required {
        &:before {
          content: "*";
          color: #fa5051;
          margin-right: 5px;
        }
      }
    }
    .block-input {
      flex: 1;
      text-align: left;
      &.right {
        text-align: right;
      }
    }
    .xuanzerenlian {
      width: 100%;
      text-align: center;
      margin-top: 10px;
    }
    .block-input-tip {
      font-size: 12px;
      color: #666;
      display: flex;
      flex-direction: row;
      align-items: center;
    }
  }
}
button::after {
  border: none !important;
}
@import "./index.scss";
</style>
